﻿using EMoney.IStock.Client.DataAccess.Boot;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.Boot;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace EMoney.IStock.Client.Business.Boot
{
    /// <summary>
    /// 开机画面业务处理类
    /// </summary>
    public class BootBll
    {
        private object objBigEvent = new object();
        private object objWeather = new object();
        private object objQsRs = new object();
        private object objHotStock = new object();
        private object objUserFunc = new object();

        private const string BIGEVENT_CACHED_KEY = "EMoney.IStock.Client.Business.Boot.BootBll.BigEvent";
        private const string WEATHER_CACHED_KEY = "EMoney.IStock.Client.Business.Boot.BootBll.Weather";
        private const string QSRS_CACHED_KEY = "EMoney.IStock.Client.Business.Boot.BootBll.Qsrs";
        private const string HOTSTOCK_CACHED_KEY = "EMoney.IStock.Client.Business.Boot.BootBll.HotStock";
        private const string USERFUNC_CACHED_KEY = "EMoney.IStock.Client.Business.Boot.BootBll.UserFunc";

        /// <summary>
        /// 获取大事件
        /// </summary>
        /// <returns></returns>
        public BigEvent GetBigEvent()
        {
            BigEvent bigEvent = CacheManager.RedisCache.Get<BigEvent>(BIGEVENT_CACHED_KEY);

            if (bigEvent == null)
            {
                try
                {
                    lock (objBigEvent)
                    {
                        bigEvent = CacheManager.RedisCache.Get<BigEvent>(BIGEVENT_CACHED_KEY);

                        if (bigEvent == null)
                        {
                            BootDal bootDal = new BootDal();

                            bigEvent = bootDal.GetBigEvent();

                            if (bigEvent != null)
                            {
                                CacheManager.RedisCache.Set<BigEvent>(BIGEVENT_CACHED_KEY, bigEvent, 30);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取大事件失败");
                }
            }

            return bigEvent;
        }

        /// <summary>
        /// 获取剩余天数
        /// </summary>
        /// <param name="userFunc"></param>
        /// <param name="dt"></param>
        private void GetRemain(UserFunc userFunc,DateTime dt)
        {
            if (dt.DayOfWeek != DayOfWeek.Sunday)
            {
                userFunc.Remain++;

                dt = dt.AddDays(1);
                GetRemain(userFunc, dt);
            }
            else
            {
                userFunc.Remain++;
            }
        }

        /// <summary>
        /// 获取周周送
        /// </summary>
        /// <returns></returns>
        public List<UserFunc> GetUserFunc(int userid)
        {
            DateTime dtNow = DateTime.Now;

            string key = string.Concat(USERFUNC_CACHED_KEY, ".", StringHelper.FormatDateTime(dtNow));

            List<UserFunc> retList = CacheManager.DefaultCache.Get<List<UserFunc>>(key);

            if (retList == null)
            {
                try
                {
                    lock (objUserFunc)
                    {
                        retList = CacheManager.DefaultCache.Get<List<UserFunc>>(key);

                        if (retList == null)
                        {
                            BootDal bootDal = new BootDal();

                            retList = new List<UserFunc>();
                            List<UserFunc> list = bootDal.GetUserFunc(userid);

                            if (list != null && list.Count > 0)
                            {
                                UserFunc curWeek = list.Find(lst => lst.BeginDate <= dtNow && lst.EndDate >= dtNow);

                                if (curWeek != null && retList.Find(rlst => rlst.Type == 1) == null)
                                {
                                    curWeek.Type = 1;
                                    GetRemain(curWeek, dtNow);

                                    retList.Add(curWeek);
                                }

                                DateTime dtPreWeek = dtNow.AddDays(-7);

                                DateTime dtPreWeekMondy = DateTimeHelper.GetMondayDate(dtPreWeek.Date);
                                DateTime dtPreWeekSundy = DateTimeHelper.GetSundayDate(dtPreWeek.Date);

                                UserFunc preWeek = list.Find(lst => lst.BeginDate >= dtPreWeekMondy.Date && lst.EndDate < dtPreWeekSundy.AddDays(1).Date);

                                if (preWeek != null && retList.Find(rlst => rlst.Type == 2) == null)
                                {
                                    preWeek.Type = 2;

                                    retList.Add(preWeek);
                                }

                                DateTime dtPPreWeek = dtPreWeek.AddDays(-7);
                                DateTime dtPPreWeekMondy = DateTimeHelper.GetMondayDate(dtPPreWeek.Date);
                                DateTime dtPPreWeekSundy = DateTimeHelper.GetSundayDate(dtPPreWeek.Date);

                                UserFunc ppreWeek = list.Find(lst => lst.BeginDate >= dtPPreWeekMondy.Date && lst.EndDate < dtPPreWeekSundy.AddDays(1).Date);

                                if (ppreWeek != null && retList.Find(rlst => rlst.Type == 3) == null)
                                {
                                    ppreWeek.Type = 3;

                                    retList.Add(ppreWeek);
                                }
                            }

                            if (retList != null && retList.Count > 0)
                            {
                                CacheManager.DefaultCache.Set<List<UserFunc>>(key, retList, 60 * 24);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取周周送失败");
                }
            }

            return retList;
        }

        /// <summary>
        /// 获取热门个股
        /// </summary>
        /// <returns></returns>
        public string GetHotStock()
        {
            string result = CacheManager.DefaultCache.Get<string>(HOTSTOCK_CACHED_KEY);

            if (string.IsNullOrEmpty(result))
            {
                try
                {
                    lock (objHotStock)
                    {
                        result = CacheManager.DefaultCache.Get<string>(HOTSTOCK_CACHED_KEY);

                        if (string.IsNullOrEmpty(result))
                        {
                            BootDal bootDal = new BootDal();
                            StringBuilder ret = new StringBuilder();

                            DataTable dtHotStock = bootDal.GetHotStock();

                            if (dtHotStock != null && dtHotStock.Rows.Count > 0)
                            {
                                string jsonData = dtHotStock.Rows[0]["JsonData"].ToString();

                                if (!string.IsNullOrEmpty(jsonData))
                                {
                                    HotStockJson hotStockObj = JsonHelper.ToObject<HotStockJson>(jsonData);

                                    if (hotStockObj != null && hotStockObj.data != null && hotStockObj.data.Count > 0)
                                    {
                                        HotStockJsonData hotStockJsonData = hotStockObj.data.Find(data => data.pname.Equals("Week", StringComparison.OrdinalIgnoreCase));

                                        if (hotStockJsonData != null && hotStockJsonData.pdata != null && hotStockJsonData.pdata.Count > 0)
                                        {
                                            foreach (string data in hotStockJsonData.pdata)
                                            {
                                                ret.Append(data.Split(',')[0]).Append(",");
                                            }

                                            result = ret.ToString();

                                            if (!string.IsNullOrEmpty(result))
                                            {
                                                CacheManager.DefaultCache.Set<string>(HOTSTOCK_CACHED_KEY, result, 30);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取热门个股失败");
                }
            }

            return result;
        }

        /// <summary>
        /// 获取股市天气
        /// </summary>
        /// <returns></returns>
        public WeatherEnty GetWeather()
        {
            WeatherEnty weather = CacheManager.DefaultCache.Get<WeatherEnty>(WEATHER_CACHED_KEY);

            if (weather == null)
            {
                try
                {
                    lock (objWeather)
                    {
                        weather = CacheManager.DefaultCache.Get<WeatherEnty>(WEATHER_CACHED_KEY);

                        if (weather == null)
                        {
                            string url = string.Concat(ConfigHelper.CmsServiceUrl, "comm/weather.ashx");

                            NetHelper net = new NetHelper();

                            string result = net.GetClientBySocket(url, Encoding.Default);

                            if (!string.IsNullOrEmpty(result))
                            {
                                weather = JsonHelper.ToObject<WeatherEnty>(result);

                                if (weather != null)
                                {
                                    CacheManager.DefaultCache.Set<WeatherEnty>(WEATHER_CACHED_KEY, weather, 30);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取股市天气失败");
                }
            }            

            return weather;
        }

        /// <summary>
        /// 获取强势弱势板块
        /// </summary>
        /// <returns></returns>
        public QsRsEnty GetQsRs()
        {
            QsRsEnty qsrs = CacheManager.DefaultCache.Get<QsRsEnty>(QSRS_CACHED_KEY);

            if (qsrs == null)
            {
                try
                {
                    lock (objQsRs)
                    {
                        qsrs = CacheManager.DefaultCache.Get<QsRsEnty>(QSRS_CACHED_KEY);

                        if (qsrs == null)
                        {
                            string url = string.Concat(ConfigHelper.CmsServiceUrl, "hangqing/bkqr.ashx");

                            NetHelper net = new NetHelper();

                            string result = net.GetClientBySocket(url, Encoding.Default);

                            if (!string.IsNullOrEmpty(result))
                            {
                                qsrs = JsonHelper.ToObject<QsRsEnty>(result);

                                if (qsrs != null)
                                {
                                    CacheManager.DefaultCache.Set<QsRsEnty>(QSRS_CACHED_KEY, qsrs, 10);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "获取强势弱势板块失败");
                }
            }            

            return qsrs;
        }
    }
}
